package com.kuaiyin.executor;

import com.kuaiyin.exception.BaseException;
import com.kuaiyin.service.ITestPlanService;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Quartz 定时任务 Job 类：用于执行测试计划
 */
@Component
public class TestPlanQuartzJob implements Job, ApplicationContextAware {

    public static final String PLAN_ID = "planId";

    private static ApplicationContext applicationContext; // 静态变量保存 Spring 上下文

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        applicationContext = ctx; // 设置静态的 ApplicationContext
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getMergedJobDataMap(); // 获取 JobDataMap 数据
        Long planId = dataMap.getLong(PLAN_ID); // 获取计划 ID

        // 从应用程序上下文中获取测试计划服务的 bean
        ITestPlanService testPlanService = applicationContext.getBean(ITestPlanService.class);

        try {
            // 调用测试计划服务的运行测试计划方法
            testPlanService.runTestPlan(planId);
        }catch (BaseException e) {
            // 计划不存在或禁用时，直接取消任务
            JobExecutionException jobException = new JobExecutionException(e);
            jobException.setUnscheduleAllTriggers(true); // 取消所有相关触发器
            throw jobException;
        } catch (Exception e) {
            throw new JobExecutionException(e);
        }
    }
}
